#include "QxSampleApp.hpp"
#include "ui_QxSampleApp.h"

#include <SampleApp/QxSampleModuleFactory.hpp>

#include <QStringListModel>
#include <QItemSelectionModel>

class QxSampleApp::QxSampleAppPrivate
{
public:

  QxSampleAppPrivate( QxSampleApp* me ) : m_self( me ) {
    m_ui.setupUi( m_self );
    m_ui.listView->setModel( &m_model );

    QObject::connect( m_ui.listView->selectionModel(), SIGNAL( selectionChanged( const QItemSelection&, const QItemSelection& ) ),
                      m_self, SLOT( slotSelectionChanged() ) );
  }

  void init() {
    QStringList pluginNameList = QxSampleModuleFactory::instance().pluginNameList();
    if( !pluginNameList.isEmpty() ) {
      m_model.setStringList( pluginNameList );
    }
  }

  QxAbstractPlugin* selectedPlugin() {
    QxAbstractPlugin* result = 0;

    QItemSelectionModel* selectionModel = m_ui.listView->selectionModel();
    QModelIndexList selectedRows = selectionModel->selectedRows();
    if( !selectedRows.isEmpty() ) {
      QString pluginName = m_model.stringList().at( selectedRows.first().row() );
      result = QxSampleModuleFactory::instance().findPluginByName( pluginName );
    }

    return result;
  }

  QxSampleApp*               m_self;
  Ui::QxSampleApp            m_ui;

  QStringListModel           m_model;
};

QxSampleApp::QxSampleApp( QWidget* parent ) : QMainWindow( parent ), _pd( new QxSampleAppPrivate( this ) )
{
  _pd->init();
}

QxSampleApp::~QxSampleApp()
{
}

void QxSampleApp::on_renderBtn_clicked()
{
  QxAbstractPlugin* thePlugin = _pd->selectedPlugin();
  if( thePlugin ) {
    QPointer<QWidget> targetWidget = thePlugin->createMainWidget();
    if( targetWidget ) {
      targetWidget->setAttribute( Qt::WA_DeleteOnClose );
      targetWidget->show();
    }
  }
}

void QxSampleApp::slotSelectionChanged()
{
  QxAbstractPlugin* thePlugin = _pd->selectedPlugin();
  if( thePlugin ) {
    _pd->m_ui.description->setText( thePlugin->description() );
  }
}
